package Solution125_150;

import org.junit.Test;
import org.omg.PortableInterceptor.INACTIVE;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

public class Solution146LRU {

    class LRUCache2{
        HashMap<Integer, Integer> dataMap;
        LinkedList<Integer> keyList;
        private int capacity;

        public LRUCache2(int capacity) {
            this.capacity = capacity;
            dataMap = new HashMap<>();
            keyList = new LinkedList<>();
        }

        public int get(int key) {
            if (dataMap.containsKey(key)) {
                keyList.remove((Object) key);
                keyList.addFirst(key);
                return dataMap.get(key);
            }
            return -1;
        }

        public void put(int key, int value) {
            if (dataMap.containsKey(key)) {
                keyList.remove((Object) key);
            } else {
                while (keyList.size() >= capacity) {
                    int eliminateKey = keyList.getLast();
                    keyList.removeLast();
                    dataMap.remove(eliminateKey);
                }
            }

            keyList.addFirst(key);
            dataMap.put(key, value);
        }
    }

    /**
     * 最优解
     */
    class LRUCache extends LinkedHashMap<Integer, Integer> {
        private int capacity;

        public LRUCache(int capacity) {
            super(capacity, 0.75F, true);
            this.capacity = capacity;
        }

        public int get(int key) {
            return super.getOrDefault(key, -1);
        }

        public void put(int key, int value) {
            super.put(key, value);
        }

        @Override
        protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
            return size() > capacity;
        }
    }



    @Test
    public void test() {
        LRUCache lruCache = new LRUCache(2);
        lruCache.get(2);
        lruCache.put(2, 6);

        lruCache.get(1);
        lruCache.put(1, 5);

        lruCache.put(1, 2);

        lruCache.get(1);
        lruCache.get(2);
    }

}
